<template>
	<view style="height: 100vh;background-color: white;">

		<view v-if="isAddStatus" >
		
				  <u-notice-bar :text="NoticeBarInfo"></u-notice-bar>
			
		</view>
		<form>
			<view class="cu-form-group">
				<view class="title">任务名称</view>
				<input placeholder="请输入任务名称" v-model="form.todo_item_name" name="input"></input>
			</view>
			<view class="cu-form-group align-start">
				<view class="title">任务描述</view>
				<textarea maxlength="-1" v-model="form.todo_item_description" placeholder="请输入任务描述"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="title">开始日期</view>
				<picker mode="date" v-model="form.todo_start_time" @change="startDateChange">
					<view class="picker">
						{{form.todo_start_time}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">结束日期</view>
				<picker mode="date" v-model="form.todo_end_time" @change="endDateChange">
					<view class="picker">
						{{form.todo_end_time}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">间隔时间 (每隔
					<span class="text-red text-bold">{{form.todo_item_loop_time}}</span>
					天执行一次)
				</view>
				<u-number-box :value="numberValue" @change="numberValueChange"></u-number-box>
			</view>


			<view class="cu-form-group">
				<view class="title ">任务排序 (当前排序为

					<span class="text-red text-bold">{{form.sort}}</span>
					)
				</view>
				<u-number-box :value="sortValue" @change="sortNumberValue"></u-number-box>
			</view>

			<view class="cu-form-group">
				<view class="title">状态</view>
				<switch class='olive round' @change="isShow" :class="form.todo_item_show?'checked':''"
					:checked="form.todo_item_show?true:false"></switch>
			</view>

			<view class="cu-form-group">
				<view class="title">是否提醒 (系统{{form.todo_item_remind?'':'不'}}发送订阅提醒)</view>
				<switch class='olive round' @change="isRemind" :class="form.todo_item_remind?'checked':''"
					:checked="form.todo_item_remind?true:false"></switch>
			</view>
			<view v-show="form.todo_item_remind" class="cu-form-group">
				<view class="title">选择提醒时间</view>
				<picker mode="time" v-model="form.todo_remind_time" @change="todo_remind_time_handler">
					<view class="picker">
						{{form.todo_remind_time}}
					</view>
				</picker>
			</view>

			<view class="padding-lg padding-top-xl flex flex-direction bg-white">
				<button :disabled="scores<=0&&isAddStatus" @click="sbumitBefore"
					:class="[scores>0||!isAddStatus?'':'']" class="cu-btn  block  lg">确定</button>
			</view>
		</form>
	</view>
</template>

<script>
	import {
		getScores,
		insert_todo_item_one,
		insert_todo_item_need_do,
		todo_item_by_pk_for_edit,
		update_todo_item_by_pk_for_edit
	} from "@/common/api.js";
	import {checkAndRequestSubscribeMessage} from "@/common/utils.js"
	export default {
		
		onLoad(option) {

			this.userInfo = uni.getStorageSync("userInfo");

			if (!this.userInfo) {
				uni.showModal({
					content: "获取用户信息失败",
					complete() {
						uni.navigateTo({
							url: "/pages/login/index"
						})
					}
				})

				return
			}
			
			
		

			if (option.type === 'add') {
				console.log(option, "add===");
				// 把用户id赋值到表单
				this.form.user_id = this.userInfo.id
				// 获取积分信息
				getScores(this.userInfo.id)
					.then((res) => {
						console.log(res, "获取积分信息");
						if (res.code === 200 && res.data.scores.length) {
							this.scores = res.data.scores[0].scores_number
							// <!-- <text class='cuIcon-title text-olive'></text>您当前有
							// <span class="text-yellow text-bold">{{scores}}</span>
							// 个积分,可以添加
							// <span class=" text-bold">{{scores}}</span>
							// 个任务!分享好友可以获取积分 -->
							this.NoticeBarInfo= `您当前有${this.scores}个积分,可以添加${this.scores}个任务!分享转发可以获得积分`
							this.no
						} else {
							console.log("获取积分信息err");
						}
					})
					.catch((err) => {
						console.log(err, "获取积分信息");
					});
				uni.setNavigationBarTitle({
					title: '添加任务'
				});
				// 添加状态

				// 初始化时间
				this.form.todo_start_time = this.$moment(new Date()).format('yyyy-MM-DD')
				this.form.todo_end_time = this.$moment(new Date((new Date() / 1000 + 86400 * 30) * 1000)).format(
					'yyyy-MM-DD')



			} else if (option.type === 'edit') {
				this.isAddStatus = false
				console.log(option, "edit===");
				uni.setNavigationBarTitle({
					title: '修改任务'
				});
				this.todo_item_id = option.id
				// 查询任务,把任务渲染到表单 // 注意:userid要用本地存储的userInfo里面的
				todo_item_by_pk_for_edit(option.id).then(res => {

					if (res.code === 200 && res.data) {
						console.log(res.data, "把任务渲染到表单res");
						// 检查查询到的任务是否是与本地存储过用户信息的用户一致
						if (res.data.todo_item_by_pk.user_id !== this.userInfo.id) {
							uni.clearStorageSync()
							uni.showModal({
								content: "获取任务失败,请重试!",
								complete() {
									uni.navigateBack(-1)
								}
							})
						}
						// 把任务赋值给表单
						this.form = res.data.todo_item_by_pk
						this.numberValue = res.data.todo_item_by_pk.todo_item_loop_time
						this.sortValue = res.data.todo_item_by_pk.sort
					} else {
						uni.showModal({
							content: "获取任务失败,请重试!",
							complete() {
								uni.navigateBack(-1)
							}
						})
					}
				}).catch(err => {
					console.log(err, "把任务渲染到表单err");
					uni.showModal({
						content: "获取任务失败,请重试!",
						complete() {
							uni.navigateBack(-1)
						}
					})
				})

			}

		},

		data() {
			return {
				NoticeBarInfo:'',
				temp:{
					todo_start_time: '',
					todo_end_time: '',
					todo_item_loop_time:1
				},
				todo_item_id:'',
				isAddStatus: true, //是否是添加状态 'add','edit'
				// 积分
				scores: 0,
				// 用户信息
				userInfo: null,

				// 表单数据
				numberValue: 1, // 间隔时间value
				sortValue: 1, // 任务排序value
				form: {
					todo_item_name: "",
					todo_item_description: "",
					todo_start_time: '2023-01-01',
					todo_end_time: '2023-02-01',
					user_id: "",
					sort: 1,
					todo_item_loop_time: 1,
					todo_item_remind: false,
					todo_remind_time: "09:00",
					todo_item_need_nums: 0, //需要执行的次数
					todo_item_show: true,
					todo_item_task_cycle: 0, //任务周期
				},

				//--------------------------------------

			};
		},

		methods: {
			// 系统提醒时间
			todo_remind_time_handler(e) {
				this.form.todo_remind_time = e.detail.value
			},
			// 是否公开任务
			isShow(e) {
				this.form.todo_item_show = e.detail.value
			},
			// 是否提醒
			isRemind(e) {
				this.form.todo_item_remind = e.detail.value
			},
			numberValueChange(e) {
				console.log(e);
				this.form.todo_item_loop_time = e.value
			},
			sortNumberValue(e) {
				this.form.sort = e.value
			},
			startDateChange(e) {
				this.form.todo_start_time = e.detail.value
			},
			endDateChange(e) {
				this.form.todo_end_time = e.detail.value
			},
			//--------------------------
			// 订阅
			sbumitBefore(){
				checkAndRequestSubscribeMessage().then(res=>{
					// console.log(res,"-------------checkAndRequestSubscribeMessageres");
					// 只要res == ok 说明已经返回到该页面,继续添加任务
				}).catch(err=>{
					console.log(err,"--------------checkAndRequestSubscribeMessageerr");
				}).finally(e=>{
					// console.log(e,"fanaliy");
					// 说明已经返回到该页面,继续添加任务
					this.submit()
				})
			},
			//提交
			submit() {
				let that = this
				
				// 提交信息
				if (this.form.todo_item_name.trim() === '') {
					uni.showToast({
						icon: "error",
						title: "任务名称不能为空!"
					})

					return
				}
				// 开始时间不能大于结束时间,也不能等于结束时间
				if (this.form.todo_start_time>=this.form.todo_end_time) {
					uni.showToast({
						icon: "error",
						title: "日期错误!"
					})
				
					return
				}
			
				
			
				// 目标占用总天数
				let allDays = this.$moment(this.form.todo_end_time).diff(this.form.todo_start_time, 'day')
				// 任务周期
				this.form.todo_item_task_cycle = allDays
				// 计算当前目标需要执行的总次数
				this.form.todo_item_need_nums = parseInt(allDays / this.form.todo_item_loop_time + 1)
				 // this.form.created_at = this.$moment().format()
				 const nowDate = this.$moment().format()
				console.log(this.form, this.form.todo_item_task_cycle, this.form.todo_item_need_nums);
			
				if (this.scores > 0 && this.isAddStatus) {
					let variables = {
						created_at:nowDate,
						updated_at:nowDate,
						...this.form
					}
					// 添加任务
					insert_todo_item_one(variables).then(res => {
						console.log(res, "添加任务");
						if (res.code === 200 && res.data?.insert_todo_item_one?.id) {
							uni.showToast({
								icon: "success",
								title: "添加成功!"
							})
							let objs = []
							for (var i = 0; i <= allDays; i = i + this.form.todo_item_loop_time) {
								// 计算目标每次执行的时间
								let obj = {
									todo_date: this.$moment(this.form.todo_start_time).add(i, 'd').format(
										"yyyy-MM-DD"),
									todo_item_id: res.data?.insert_todo_item_one?.id,
									user_id: this.form.user_id,
									created_at:nowDate
									
								}
								objs.push(obj)
							}
							insert_todo_item_need_do(objs).then(res => {
								console.log(res, "添加执行次数及每次的执行时间");
							}).catch(err => {
								console.log(err, "添加执行次数及每次的执行时间");
							})
							//跳转到首页
							setTimeout(function() {
								uni.switchTab({
									url: '/pages/index/index'
								});
							}, 500);

						}
					}).catch(err => {
						console.log(err, "添加任务");
						uni.showToast({
							icon: "error",
							title: "添加失败!"
						})
					})
				} else if (this.scores === 0 && !this.isAddStatus) {
					// 修改
					
					console.log("修改");
					// 修改之前,先删除执行序列,修改之后再新增执行系列(数据库写个trigger)
					// 先写修改的api,写好修改一条看看,修改成功以后
					// 写trigger删除序列,修改之前删除,因为修改之后马上有插入序列操作
					delete this.form.user_id
					let variables = {
						"id": this.todo_item_id,
						"_set": {
							...this.form,
							
							updated_at:nowDate,
						}
					}
					update_todo_item_by_pk_for_edit(variables).then(res=>{
						console.log(res,"修改任务res");
						if(res.data?.update_todo_item_by_pk){
							// 修改成功,说明原来的待办次数已经删除,添加新的待办记录
						
							if(this.temp.todo_start_time!==this.form.todo_start_time||
							this.temp.todo_end_time!==this.form.todo_end_time||
							this.temp.todo_item_loop_time!==this.form.todo_item_loop_time
							){ // 如果修改过任务开始时间,任务结束时间,间隔时间其中之一才添加新的待办提醒
								let objs = []
								for (var i = 0; i <= allDays; i = i + this.form.todo_item_loop_time) {
									// 计算目标每次执行的时间
									let obj = {
										todo_date: this.$moment(this.form.todo_start_time).add(i, 'd').format(
											"yyyy-MM-DD"),
										todo_item_id: res.data?.update_todo_item_by_pk?.id,
										user_id: res.data?.update_todo_item_by_pk?.user_id,
										created_at:nowDate,
									}
									objs.push(obj)
								}
								insert_todo_item_need_do(objs).then(res => {
									console.log(res, "添加执行次数及每次的执行时间");
								}).catch(err => {
									console.log(err, "添加执行次数及每次的执行时间");
								})
							}
							
							
								uni.showModal({
									content: "修改成功!",
									complete() {
										uni.navigateBack(-1)
									}
								})
							
						
							
						}else{
							uni.showModal({
								content: "修改失败,请重试!",
								complete() {
									uni.navigateBack(-1)
								}
							})
						}
					}).catch(err=>{
						console.log(err,"修改任务err");
						uni.showModal({
							content: "修改失败,请重试!",
							complete() {
								uni.navigateBack(-1)
							}
						})
					})
				}



			},
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
